package boardgamer.common.client;

import android.graphics.Canvas;
import android.graphics.RectF;
import boardgamer.common.client.layout.InvisibleRect;
import boardgamer.common.client.layout.LayoutGroup;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Simple button with event handler.
 *
 * @author garysoed
 */
public class SimpleButton implements Button {

  private final LayoutGroup displayGroup;
  private final Drawable display;
  private final InvisibleRect collisionBox;
  private final EventHandler eventHandler;

  public SimpleButton(
      Display display, EventHandler eventHandler, RectF collisionBox) {
    this.display = checkNotNull(display, "display");
    this.collisionBox = new InvisibleRect(checkNotNull(collisionBox, "collisionBox"));
    this.eventHandler = checkNotNull(eventHandler, "eventHandler");
    this.displayGroup = new LayoutGroup();
    this.displayGroup
        .add(display).atCurrentRect()
        .add(this.collisionBox).atCurrentRect();
  }

  @Override
  public void draw(Canvas canvas) {
    display.draw(canvas);
  }

  @Override
  public void handleEvent(float eventX, float eventY, int eventAction) {
    if (collisionBox.getBoundingRect().contains(eventX, eventY)) {
      eventHandler.onEvent(eventX, eventY, eventAction);
    }
  }

  @Override
  public RectF getCollisionBox() {
    return new RectF(collisionBox.getBoundingRect());
  }

  @Override
  public void setBoundingRect(RectF boundingRect) {
    displayGroup.setBoundingRect(boundingRect);
  }

  @Override
  public RectF getBoundingRect() {
    return new RectF(displayGroup.getBoundingRect());
  }
}
